package com.aliyun.oss;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 * 声明bean的注解，成为ioc容器中的bean对象，@Controller、@Service和@Repository都是@Component注解的派生注解
 * - @Value注解只能一个一个的进行外部属性的注入。
 * - @ConfigurationProperties可以批量的将外部的属性配置注入到bean对象的属性中。
 */
//@Component
public class AliOSSUtils {

/*    写在配置文件application.properties里面了
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5t9PjsSRw4Cyb2xWxz9D";
    private String accessKeySecret = "9dCnSNlYQ9rIkzG01nfTttYIKgwHIt";
    private String bucketName = "lan-web-tlias";*/
    /*
    private String endpoint;//    @Value()  注释可以注入下面四个的值，在application.yml里
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
*/
   /* @Autowired
    private AliOSSProperties aliOSSProperties;*/

    private AliOSSProperties aliOSSProperties;

    public AliOSSProperties getAliOSSProperties() {
        return aliOSSProperties;
    }

    public void setAliOSSProperties(AliOSSProperties aliOSSProperties) {
        this.aliOSSProperties = aliOSSProperties;
    }

    /**
     * 实现上传图片到OSS
     */
    //upload不是静态方法，要调用的话还要new对象，但是在spring环境，所以加上注解交给ioc容器管理
    public String upload(MultipartFile file) throws IOException {
        //获取阿里云oss参数
        String endpoint = aliOSSProperties.getEndpoint();
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String bucketName = aliOSSProperties.getBucketName();

        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}
